package com.gxa.autoparts.admin.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.google.gson.JsonObject;
import com.gxa.autoparts.admin.mapper.GoodsMapper;
import com.gxa.autoparts.admin.service.*;
import com.gxa.autoparts.admin.vo.AddGoodsVo;
import com.gxa.autoparts.core.common.JsonResult;
import com.gxa.autoparts.core.pojo.*;
import com.gxa.autoparts.core.util.GetMinUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import javax.annotation.Resources;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//商品商城所i有接口controller
@RestController
@RequestMapping("/shop")
@Api
public class ShopManagementController {



    @Autowired
    ShopManagementService shopManagementService;
    @Autowired
    GoodsService goodsService;
    @Autowired
    AttributeKeyService attributeKeyService;
    @Autowired
    KeyWordsService keyWordsService;
    @Resource
    GoodsMapper goodsMapper;
    @Autowired
    GoodsTypeService goodsTypeService;
    @Autowired
    GoodsImgService goodsImgService;
    @Resource
    GoodsSkuService goodsSkuService;
    @Resource
    GoodsPropertiesService goodsPropertiesService;
    @Resource
    SecondKillService secondKillService;
    @Resource
    RushBuyService rushBuyService;
    @Autowired
    RedisTemplate<String,Object> redisTemplate;

    private static final String SKU_CATCH = "skuCatch:";//库存
    private static final String KILL_Time = "killTime:";//时间（list）
    //分页全查返回商品信息
    @ApiOperation("分页全查返回商品信息")
    @PostMapping("/selectAllGoods")
    @ApiImplicitParams({@ApiImplicitParam(name = "page",value = "第几页",required = true),
            @ApiImplicitParam(name = "size",value = "多少条数据",required = true)
    })
    public Map selectAllGoods(Integer page,Integer size) throws Exception {
        List<Goods> goods = goodsService.selectAllGoods(page, size);
        List<Goods> goods1 = goodsMapper.selectAllGoodsAll();
        int size1 = goods1.size();
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(goods);
        jsonResult.put("count",size1);
        return jsonResult.getDataMap();
    }
    //获取一级分类
    @PostMapping("/selectGoodsType")
    @ApiOperation("获取一级分类")
    public Map selectGoodsType(){
        List<GoodsType> goodsTypes = shopManagementService.selectTypeAll();
        List list = new ArrayList();
        for (GoodsType goodsType : goodsTypes) {
            String name = goodsType.getName();
            list.add(name);
        }
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(list);
        return jsonResult.getDataMap();
    }
    //通过一级分类获得二级分类的名字
    @PostMapping("/selectTwoGoodsType")
    @ApiOperation("通过一级分类获得二级分类的名字")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value = "一级分类名字",required = true)
    })
    public Map selectTwoGoodsType(String name) throws Exception {
        GoodsType goodsType1 = goodsService.selectGoodsTypeByName(name);
        Long id = goodsType1.getId();
        List<GoodsType> goodsTypes1 = goodsService.selectGoodsTypeById(id);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(goodsTypes1);
        return jsonResult.getDataMap();
    }
    //商品列表搜索的接口
    @PostMapping("/selectByPidAndGoodsName")
    @ApiOperation("商品列表搜索的接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pid",value = "goodType_id",required = false),
            @ApiImplicitParam(name = "name",value = "商品名字",required = false),
            @ApiImplicitParam(name = "page",value = "第几页",required = true),
            @ApiImplicitParam(name = "size",value = "多少条数据",required = true)
    })
    public Map selectByPidAndGoodsName(Long pid, String name, Integer page, Integer size) throws Exception {
        List<Map> goods = goodsService.selectByPidAndGoodsName(pid, name, page, size);
        int size1 = goods.size();
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(goods);
        jsonResult.put("count",size1);
        return jsonResult.getDataMap();
    }
    /*//返回属性名称
    @PostMapping("/selectAllAttributeKey")
    @ApiOperation("返回属性名称")
    public Map selectAllAttributeKey(){
        List<AttributeKey> attributeKeys = attributeKeyService.selectAll();
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(attributeKeys);
        return jsonResult.getDataMap();
    }
    @PostMapping("/selectAttributeValueById")
    @ApiOperation("根据对应的attributeKeyId查找对应的一些attributeValue")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "attributeKeyId",value = "商品属性keyId",required = true)
    })
    public Map selectAttributeValueById(Long attributeKeyId){
        List<AttributeValue> attributeValues = attributeKeyService.selectAttributeValueById(attributeKeyId);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(attributeValues);
        return jsonResult.getDataMap();
    }*/
    @PostMapping("/selectAllAttributeKeyNameAndAttributeValueName")
    @ApiOperation("返回商品属性值以及商品属性")
    public Map selectAllAttributeKeyNameAndAttributeValueName(Long attributeKeyId,String name) throws Exception {
        List<AttributeKey> attributeKeys = attributeKeyService.selectAllAttributeKeyNameAndAttributeValueName(attributeKeyId);
        GoodsType goodsType = goodsService.selectGoodsTypeByName(name);
        Long id = goodsType.getId();
        List<AttributeKey> attributeKeys1 = attributeKeyService.selectAttributeKeyAndAttributeValue(id);
        for (AttributeKey attributeKey : attributeKeys1) {

        }
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(attributeKeys);
        return jsonResult.getDataMap();
    }
    @PostMapping("/selectAllKeyWords")
    @ApiOperation("返回所有的关键字")
    public Map selectAllKeyWords(){
        List<KeyWords> keyWords = keyWordsService.selectAll();
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(keyWords);
        return jsonResult.getDataMap();
    }
    @PostMapping("/addGoods")
    @ApiOperation("增加商品")
    public Map addGoods(Long pid,String goodsName,String img,List list){
return null;
    }



    @PostMapping("/addFirstKind")
    @ApiOperation("增加第一类别")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value = "类别",required = true)
    })
    public Map addFirstKind(String name){
        GoodsType goodsType = new GoodsType();
        goodsType.setPid(0L);
        goodsType.setName(name);
        goodsTypeService.insert(goodsType);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getDataMap();
    }
    @PostMapping("/addSecondKind")
    @ApiOperation("增加第二类别")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pid",value = "类别pid",required = true),
            @ApiImplicitParam(name = "name",value = "类别名字",required = true)
    })
    public Map addSecondKind(Long pid,String name){
        GoodsType goodsType = new GoodsType();
        goodsType.setPid(pid);
        goodsType.setName(name);
        goodsTypeService.insert(goodsType);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getDataMap();
    }
    @PostMapping("/updateKind")
    @ApiOperation("编辑类别")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "类别id",required = true),
            @ApiImplicitParam(name = "name",value = "类别名字",required = true)
    })
    public Map updateKind(Long id,String name){
        GoodsType goodsType1 = goodsTypeService.selectById(id);
        //GoodsType goodsType = goodsService.selectGoodsTypeByName(name);
        goodsType1.setName(name);
        goodsTypeService.updateById(goodsType1);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getDataMap();
    }
    @PostMapping("/selectGoodsTypeByName")
    @ApiOperation("通过类别名字查找返回对应类别的id")
    public Map selectGoodsTypeByName(String name) throws Exception {
        GoodsType goodsType = goodsService.selectGoodsTypeByName(name);
        Long id = goodsType.getId();
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.put("id",id);
        return jsonResult.getDataMap();
    }
    @PostMapping("/deleteKind")
    @ApiOperation("删除类别")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value = "类别名字",required = true)
    })
    public Map deleteKind(String name) throws Exception {
        GoodsType goodsType = goodsService.selectGoodsTypeByName(name);
        Long id = goodsType.getId();
        goodsTypeService.deleteById(id);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getDataMap();
    }
    @PostMapping("/selectKeyWords")
    @ApiOperation("页面显示基本关键词")
    public Map selectKeyWords(){
        List<KeyWords> keyWords = keyWordsService.selectKeyWords();
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(keyWords);
        return jsonResult.getDataMap();
    }
    @PostMapping("/addKeyWords")
    @ApiOperation("增加关键词")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value = "关键词名字",required = true)
    })
    public Map addKeyWords(String name){
        KeyWords keyWords = new KeyWords();
        keyWords.setGoodsId(1000L);
        keyWords.setName(name);
        keyWordsService.insert(keyWords);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getDataMap();
    }
    @PostMapping("/deleteKeyWords")
    public Map deleteKeyWords(String name){
        KeyWords keyWords = keyWordsService.deleteKeyWords(name);
        Long id = keyWords.getId();
        keyWordsService.deleteById(id);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getDataMap();
    }
    @PostMapping("/addGood")
    public Map addGoods(@RequestBody AddGoodsVo addGoodsVo){
        /*Boolean state = Boolean.valueOf(map.get("state").toString());
        Long pid = Long.valueOf(map.get("pid").toString());
        String goodsName = map.get("goodsName").toString();
        String img = map.get("img").toString();
        String detail = map.get("detail").toString();
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Object sku = map.get("sku");
        List list=(List) sku;*/
        Boolean state = addGoodsVo.getState();
        Long pid = addGoodsVo.getPid();
        String img = addGoodsVo.getImg();
        String goodsName = addGoodsVo.getGoodsName();
        String detail = addGoodsVo.getDetail();
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        List<Map<String, Object>> sku = addGoodsVo.getSku();
        List<Double> arr=new ArrayList<>();
        for (Map<String, Object> stringObjectMap : sku) {
            double price1 = Double.parseDouble(stringObjectMap.get("price").toString());
            arr.add(price1);
        }
        double price = GetMinUtil.minArray(arr);
        List<Double> ayy=new ArrayList<>();
        for (Map<String, Object> stringObjectMap : sku) {
            double markPrice1 = Double.parseDouble(stringObjectMap.get("markPrice").toString());
            ayy.add(markPrice1);
        }
        double markPrice = GetMinUtil.minArray(ayy);
        Goods goods = new Goods();
        goods.setState(state);
        goods.setTypeId(pid);
        goods.setImg(img);
        goods.setName(goodsName);
        goods.setDetail(detail);
        goods.setUpdateTime(timestamp);
        goods.setSalePrice(price);
        goods.setRemarkPrice(markPrice);
        goodsService.insert(goods);
        Long id = goods.getId();
        System.out.println("当前添加商品id为："+id);
        List<Map<String, String>> imgs = addGoodsVo.getImgs();
        for (Map<String, String> stringStringMap : imgs) {
            GoodsImg goodsImg = new GoodsImg();
            String imgName = stringStringMap.get("imgName");
            goodsImg.setGoodsId(id);
            goodsImg.setImg(imgName);
            GoodsImg insert1 = goodsImgService.insert(goodsImg);
            System.out.println(insert1.getGoodsId());
        }


        for (Map<String, Object> stringObjectMap : sku) {
            String product = stringObjectMap.get("product").toString();
            Long count = Long.parseLong(stringObjectMap.get("count").toString());
            double price1 = Double.parseDouble(stringObjectMap.get("price").toString());
            double markPrice1 = Double.parseDouble(stringObjectMap.get("markPrice").toString());
            GoodsSku goodsSku = new GoodsSku();
            goodsSku.setGoodsId(id);
            goodsSku.setCount(count);
            int i = product.indexOf("-");
            String color = product.substring(0,i);
            String size1 = product.substring(i + 1);
            String size=size1+"cm";
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("颜色",color);
            map.put("尺寸",size);
            String json = JSON.toJSONString(map);
            StringBuilder Product = new StringBuilder();
            goodsSku.setProductSpecs(json);
            goodsSku.setPrice(price1);
            goodsSku.setMarkPrice(markPrice1);
            GoodsSku insert1 = goodsSkuService.insert(goodsSku);
        }
        List<Map<String, String>> keyWords = addGoodsVo.getKeyWords();
        for (Map<String, String> keyWord : keyWords) {
            String keyName = keyWord.get("keyName");
            KeyWords keyWords1 = new KeyWords();
            keyWords1.setGoodsId(id);
            keyWords1.setName(keyName);
            KeyWords insert1 = keyWordsService.insert(keyWords1);
        }
        GoodsProperties goodsProperties = new GoodsProperties();
        goodsProperties.setGoodsId(id);
        goodsProperties.setIsNew(false);
        goodsProperties.setIsNormal(false);
        goodsProperties.setIsSecondKill(false);
        goodsProperties.setIsTimeLimit(false);
        List<Map<String, String>> properties = addGoodsVo.getProperties();
        for (Map<String, String> property : properties) {
            String proName = property.get("proName");
            if(proName.equals("普通商品")){
                goodsProperties.setIsNormal(true);
            }
            if(proName.equals("新品")){
                goodsProperties.setIsNew(true);
            }
            if(proName.equals("秒杀商品")){
                goodsProperties.setIsSecondKill(true);
            }
            if(proName.equals("限时抢购商品")){
                goodsProperties.setIsTimeLimit(true);
            }
        }
        GoodsProperties insert1 = goodsPropertiesService.insert(goodsProperties);
        List<Map<String, String>> killTime = addGoodsVo.getKillTime();
        for (Map<String, String> stringStringMap : killTime) {
            String ktime = stringStringMap.get("ktime");
            Long aLong = redisTemplate.opsForList().leftPush(KILL_Time + id, ktime);
            SecondKill secondKill = new SecondKill();
            secondKill.setGoodsId(id);
            secondKill.setKillNumber(100L);
            secondKill.setSecondKillTime(ktime);
            SecondKill insert2 = secondKillService.insert(secondKill);
        }
        List<Map<String, String>> shopTime = addGoodsVo.getShopTime();
        for (Map<String, String> stringStringMap : shopTime) {
            String stime = stringStringMap.get("stime");
            RushBuy rushBuy = new RushBuy();
            rushBuy.setGoodsId(id);
            rushBuy.setKillNumber(100L);
            rushBuy.setStartTime(stime);
            RushBuy insert2 = rushBuyService.insert(rushBuy);
        }
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getDataMap();
    }
    @PostMapping("/selectGoodsAllKind")
    @ApiOperation("通过id查到商品所有属性")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id",value = "商品id",required = true)
    })
    public Map selectGoodsAllKind(Long id){
        Map map = goodsService.selectGoodsAllKind(id);
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        jsonResult.setData(map);
        return jsonResult.getDataMap();
    }
    @PostMapping("/updateGoods")
    @ApiOperation("编辑商品所有信息")
    public Map updateGoods(@RequestBody AddGoodsVo addGoodsVo){
        Long goodsId = addGoodsVo.getGoodsId();
        System.out.println(goodsId);
        Boolean state = addGoodsVo.getState();
        Long pid = addGoodsVo.getPid();
        String img = addGoodsVo.getImg();
        String goodsName = addGoodsVo.getGoodsName();
        String detail = addGoodsVo.getDetail();
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        List<Map<String, Object>> sku = addGoodsVo.getSku();
        List<Double> arr=new ArrayList<>();
        for (Map<String, Object> stringObjectMap : sku) {
            double price1 = Double.parseDouble(stringObjectMap.get("price").toString());
            arr.add(price1);
        }
        double price = GetMinUtil.minArray(arr);
        List<Double> ayy=new ArrayList<>();
        for (Map<String, Object> stringObjectMap : sku) {
            double markPrice1 = Double.parseDouble(stringObjectMap.get("markPrice").toString());
            ayy.add(markPrice1);
        }
        double markPrice = GetMinUtil.minArray(ayy);
        goodsMapper.updateGoods(goodsName,pid,state,img,detail,timestamp,price,markPrice,goodsId);
        //goodsService.updateById(goods);
        //Map map = goodsService.selectGoodsAllKind(goodsId);
        List<Map<String, String>> imgs = addGoodsVo.getImgs();
        for (Map<String, String> stringStringMap : imgs) {
            GoodsImg goodsImg = new GoodsImg();
            String imgName = stringStringMap.get("imgName");
            goodsImg.setGoodsId(goodsId);
            goodsImg.setImg(imgName);
            goodsImgService.updateById(goodsImg);
        }
        for (Map<String, Object> stringObjectMap : sku) {
            String product = stringObjectMap.get("product").toString();
            Long count = Long.parseLong(stringObjectMap.get("count").toString());
            double price1 = Double.parseDouble(stringObjectMap.get("price").toString());
            double markPrice1 = Double.parseDouble(stringObjectMap.get("markPrice").toString());
            GoodsSku goodsSku = new GoodsSku();
            goodsSku.setGoodsId(goodsId);
            goodsSku.setCount(count);
            int i = product.indexOf("-");
            String color = product.substring(0,i);
            String size1 = product.substring(i + 1);
            String size=size1+"cm";
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("颜色",color);
            map.put("尺寸",size);
            String json = JSON.toJSONString(map);
            StringBuilder Product = new StringBuilder();
            goodsSku.setProductSpecs(json);
            goodsSku.setPrice(price1);
            goodsSku.setMarkPrice(markPrice1);
            goodsSkuService.updateById(goodsSku);
        }
        List<Map<String, String>> keyWords = addGoodsVo.getKeyWords();
        for (Map<String, String> keyWord : keyWords) {
            String keyName = keyWord.get("keyName");
            KeyWords keyWords1 = new KeyWords();
            keyWords1.setGoodsId(goodsId);
            keyWords1.setName(keyName);
            keyWordsService.updateById(keyWords1);
        }
        GoodsProperties goodsProperties = new GoodsProperties();
        goodsProperties.setGoodsId(goodsId);
        goodsProperties.setIsNew(false);
        goodsProperties.setIsNormal(false);
        goodsProperties.setIsSecondKill(false);
        goodsProperties.setIsTimeLimit(false);
        List<Map<String, String>> properties = addGoodsVo.getProperties();
        for (Map<String, String> property : properties) {
            String proName = property.get("proName");
            if(proName.equals("普通商品")){
                goodsProperties.setIsNormal(true);
            }
            if(proName.equals("新品")){
                goodsProperties.setIsNew(true);
            }
            if(proName.equals("秒杀商品")){
                goodsProperties.setIsSecondKill(true);
            }
            if(proName.equals("限时抢购商品")){
                goodsProperties.setIsTimeLimit(true);
            }
        }
        goodsPropertiesService.updateById(goodsProperties);
        List<Map<String, String>> killTime = addGoodsVo.getKillTime();
        for (Map<String, String> stringStringMap : killTime) {
            String ktime = stringStringMap.get("ktime");
            Long aLong = redisTemplate.opsForList().leftPush(KILL_Time + goodsId, ktime);
            SecondKill secondKill = new SecondKill();
            secondKill.setGoodsId(goodsId);
            secondKill.setKillNumber(100L);
            secondKill.setSecondKillTime(ktime);
            secondKillService.updateById(secondKill);
        }
        List<Map<String, String>> shopTime = addGoodsVo.getShopTime();
        for (Map<String, String> stringStringMap : shopTime) {
            String stime = stringStringMap.get("stime");
            RushBuy rushBuy = new RushBuy();
            rushBuy.setGoodsId(goodsId);
            rushBuy.setKillNumber(100L);
            rushBuy.setStartTime(stime);
            rushBuyService.updateById(rushBuy);
        }
        JsonResult jsonResult=new JsonResult();
        jsonResult.setCode("200");
        return jsonResult.getDataMap();
    }
    /*{
        "goodsId":"1",
        "state":"1",
        "pid":"1",
        "goodsName":"商品名字",
        "img":"封面图片",
        "imgs":
        [
        {"imgName":"第一张图片名字"},
        {"imgName":"第二章图片名字"}...
                ],
        "sku":[
        {"product":"{"颜色"："红色","尺寸":"10cm"}","count":"库存数量","price":"售价","markPrice":"市场价"},
        {"product":"{"颜色"："黑色","尺寸":"20cm"}","count":"库存数量","price":"售价","markPrice":"市场价"}...
            ],
        "keyWords":[
        {"keyName":"第一个关键词"},
        {"keyName":"第二个关键词"}...
                ],
        "properties":[
        {"proName":"第一个商品属性"},
        {"proName"："第二个商品属性"}....
                ],
        "killTime":[
        {"ktime":"第一个秒杀时间"},
        {"ktime":"第二个秒杀时间"}...
                ],
        "shopTime":[
        {"stime":"第一个抢购时间"},
        {"stime":"第二个抢购时间"}...
                ],
        "detail":"商品详情1"
            }*/
   // }
/*    {
        "detail": "string",
            "goodsName": "string",
            "img": "string",
            "imgs": [

        {"imgName": "string"},
        {"imgName": "string"},
        {"imgName": "string"}

  ],
        "keyWords": [

        {"keyName": "string"},
        {"keyName": "string"},
        {"keyName": "string"}

  ],
        "killTime": [

        {"ktime": "string"},
        {"ktime": "string"},
        {"ktime": "string"}

  ],
        "pid": 4,
            "properties": [

        {"proName": "string"},
        {"proName": "string"},
        {"proName": "string"}

  ],
        "shopTime": [

        {"stime": "string"},
        {"stime": "string"},
        {"stime": "string"}

  ],
        "sku": [

        {"product":"{"颜色"："红色","尺寸":"10"}","count":"100","price":"99","markPrice":"100"},
        {"product":"{"颜色"："红色","尺寸":"20"}","count":"100","price":"99","markPrice":"102"},
        {"product":"{"颜色"："红色","尺寸":"30"}","count":"100","price":"88","markPrice":"103"}

  ],
        "state": true
    }*/




}
